package TestCases;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Random;
import java.util.Set;
  
// https://www.shuzhiduo.com/A/LPdo6lG253/
public class RandomUtils {
    private static Random random = new Random();
    
    //双重校验锁获取一个Random单例
    public static Random getRandom() {
        if(random==null){
            synchronized (RandomUtils.class) {
                if(random==null){
                    random =new Random();
                }
            }
        }
        return random;
    }
 
    /**
     * 获得一个[0,max)之间的整数。
     * @param max
     * @return
     */
    public static int getRandomInt(int max) {
//        return Math.abs(getRandom().nextInt())%max;
        // 直接返回[0, bound)范围内的随机数
        return random.nextInt(max);
    }
 
    /**
     * 获得一个[0,max)之间的整数。
     * @param max
     * @return
     */
    public static long getRandomLong(long max) {
        return Math.abs(getRandom().nextInt())%max;
    }
 
    /**
     * 从list中随机取得一个元素
     * @param list
     * @return
     */
    public static <E> E getRandomElement(List<E> list){
        return list.get(getRandomInt(list.size()));
    }

    /**
     * 泛型方法，适用于任何类型的数组
     * 从任何类型数组中随机取得一个元素
     * @param String[]、Integer[]等
     * @return
     */
    public static <E> E getRandomElement(E[] elements){
        int randomIndex = random.nextInt(elements.length);
        return elements[randomIndex];
    }
 
    /**
     * 从set中随机取得一个元素
     * @param set
     * @return
     */
    public static <E> E getRandomElement(Set<E> set){
        int rn = getRandomInt(set.size());
        int i = 0;
        for (E e : set) {
            if(i==rn){
                return e;
            }
            i++;
        }
        return null;
    }
 
    /**
     * 从map中随机取得一个key
     * @param map
     * @return
     */
    public static <K,V> K getRandomKeyFromMap(Map<K,V> map) {
        int rn = getRandomInt(map.size());
        int i = 0;
        for (K key : map.keySet()) {
            if(i==rn){
                return key;
            }
            i++;
        }
        return null;
    }
 
    /**
     * 从map中随机取得一个value
     * @param map
     * @return
     */
    public static <K,V> V getRandomValueFromMap(Map<K,V> map) {
        int rn = getRandomInt(map.size());
        int i = 0;
        for (V value : map.values()) {
            if(i==rn){
                return value;
            }
            i++;
        }
        return null;
    }
 
    /**
     * 从map中随机取得一个key,value
     * @param map
     * @return
     */
    public static Map<String,String> getRandomFromMap(Map<String,String> map) {
        int rn = getRandomInt(map.size());
        int i = 0;
        Map<String,String> maps = new HashMap<>();
        for (Entry<String, String> entry : map.entrySet()) {
            if(i==rn){
                 maps.put(entry.getKey(), entry.getValue());
            }
            i++;
        }
        return maps;
    }
    
    /**
     * 从map中根据比例取得一个key,value
     * @param map
     * @return
     */
    public static Map<String,String> getScale(Map<String,String> map) {
        int rn = getRandomInt(map.size());
        int i = 0;
        Map<String,String> maps = new HashMap<>();
        for (Entry<String, String> entry : map.entrySet()) {
            if(i==rn){
                 maps.put(entry.getKey(), entry.getValue());
            }
            i++;
        }
        return maps;
    }
    
    /**
     * 随机生成一个mac地址
     * @param map
     * @return
     */
    private static String generateMacAddress() {
        byte[] macAddr = new byte[6];
        random.nextBytes(macAddr);
        macAddr[0] = (byte) (macAddr[0] & (byte) 254);  // zeroing last 2 bits to make it unicast and locally administered

        StringBuilder sb = new StringBuilder(18);
        for (byte b : macAddr) {
            if (sb.length() > 0)
                sb.append(":");
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 随机生成多个mac地址
     * @param map
     * @return
     */
    public static String[] generateMacAddresses(int numberOfMacs) {
        String[] macAddresses = new String[numberOfMacs];
        for (int i = 0; i < numberOfMacs; i++) {
            macAddresses[i] = generateMacAddress();
        }
        return macAddresses;
    }


    // 生成单个随机IPv4地址
    private static String generateIPAddress() {
        return random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256) + "." + random.nextInt(256);
    }

    // 生成多个随机IPv4地址
    public static String[] generateIPAddresses(int numberOfIPs) {
        String[] ipAddresses = new String[numberOfIPs];
        for (int i = 0; i < numberOfIPs; i++) {
            ipAddresses[i] = generateIPAddress();
        }
        return ipAddresses;
    }

    
    /**
     * 随机生成姓名
     * @param map
     * @return
     */
    public static String createName(){
        String line = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏水窦" +
                "章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞仁袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅" +
                "皮卞齐康伍余元卜顾孟平黄和穆萧尹姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜" +
                "阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡";
        Random random = new Random();
        String name = line.charAt(random.nextInt(line.length()))+"";
        for(int i= 1+random.nextInt(2);i>0;i--){
            name+=line.charAt(random.nextInt(line.length()))+"";
        }
        return name;
    }
	
    public static JSONObject getAuditRecord(String operType,String operSentence,String scale) {
    	 Map<String, Object> auditRecordMap = new HashMap<>();
         auditRecordMap.put("operType", operType);
         auditRecordMap.put("operSentence", operSentence);
         auditRecordMap.put("scale", scale);
         JSONObject jsonObject = new JSONObject(auditRecordMap);
         return jsonObject;
    }
    
    public static void main(String[] args) throws ParseException {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 12; i++) {
            set.add(i);
        }
        for (int i = 0; i < 10; i++) {
//          System.out.println(getRandomElement(set));
        }
        
        Map<String,String> map = new HashMap<String,String>();
        map.put("drop","DROP DATABASE TEST;");
        map.put("create","CREATE DATABASE TEST;");
        map.put("show","SHOW DATABASE();");
        map.put("use","USE (TEST);");
        map.put("drop","DROP TABLE `TEST`.`JDBC`;");
        map.put("create","CREATE TABLE IF NOT EXISTS `TEST`.`JDBC`("
        		+ "   `id` INT UNSIGNED AUTO_INCREMENT,"
        		+ "   `name` VARCHAR(100) NOT NULL,"
        		+ "   `float` FLOAT NOT NULL,"
        		+ "   `long` LONGTEXT NOT NULL,"
        		+ "   `date` DATE,"
        		+ "   PRIMARY KEY ( `id` )"
        		+ ")ENGINE=InnoDB DEFAULT CHARSET=utf8;");
        map.put("insert","INSERT INTO `TEST`.`JDBC` VALUES (1, '小王', 5/3,5/3,SYSDATE());");
        map.put("delete","DELETE FROM `TEST`.`JDBC` WHERE id=2;");
        map.put("update","UPDATE `TEST`.`JDBC` SET name='小李' WHERE id=1;");
        map.put("select","SELECT * FROM `TEST`.`JDBC`;");
//        System.out.println(map);
        for (int i = 0; i < 10; i++) {
//            System.out.println(getRandomKeyFromMap(map));
//            System.out.println(getRandomFromMap(map));
        }
        
        
        JSONObject sql1 = getAuditRecord("drop","DROP DATABASE TEST;","3%");
        JSONObject sql2 = getAuditRecord("create","CREATE DATABASE TEST;","17%");
        JSONObject sql3 = getAuditRecord("show","SHOW DATABASE;","10%");
        JSONObject sql4 = getAuditRecord("use","USE (TEST);","10%");
        JSONObject sql5 = getAuditRecord("drop","DROP TABLE `TEST`.`JDBC`;","10%");
        JSONObject sql6 = getAuditRecord("create","CREATE TABLE IF NOT EXISTS `TEST`.`JDBC`("
        		+ "   `id` INT UNSIGNED AUTO_INCREMENT,"
        		+ "   `name` VARCHAR(100) NOT NULL,"
        		+ "   `float` FLOAT NOT NULL,"
        		+ "   `long` LONGTEXT NOT NULL,"
        		+ "   `date` DATE,"
        		+ "   PRIMARY KEY ( `id` )"
        		+ ")ENGINE=InnoDB DEFAULT CHARSET=utf8;","10%");
        JSONObject sql7 = getAuditRecord("insert","INSERT INTO `TEST`.`JDBC` VALUES (1, '小王', 5/3,5/3,SYSDATE());","10%");
        JSONObject sql8 = getAuditRecord("delete","DELETE FROM `TEST`.`JDBC` WHERE id=2;","10%");
        JSONObject sql9 = getAuditRecord("update","UPDATE `TEST`.`JDBC` SET name='小李' WHERE id=1;","10%");
        JSONObject sql10 = getAuditRecord("select","SELECT * FROM `TEST`.`JDBC`;","10%");
        
        List<JSONObject> list = new ArrayList<JSONObject>();
		list.add(sql1);
		list.add(sql2);
		list.add(sql3);
		list.add(sql4);
		list.add(sql5);
		list.add(sql6);
		list.add(sql7);
		list.add(sql8);
		list.add(sql9);
		list.add(sql10);
		
        JSONArray Cases = new JSONArray();
        JSONObject Case = new JSONObject(true);

        int count = 100;
//        Double scale = NumberFormat.getPercentInstance().parse(sql1.getString("scale")).doubleValue();
//		for (int i = 0; i < count*scale; i++) {
//			Case = new JSONObject(true);
//			Case.put("operType", sql1.get("operType"));
//			Case.put("operSentence", sql1.get("operSentence"));
//			Cases.add(Case);
//		}
//		scale = NumberFormat.getPercentInstance().parse(sql6.getString("scale")).doubleValue();
//		for (int i = 0; i < count*scale; i++) {
//			Case = new JSONObject(true);
//			Case.put("operType", sql6.get("operType"));
//			Case.put("operSentence", sql6.get("operSentence"));
//			Cases.add(Case);
//		}
//		System.out.println(Cases);
        long start=System.currentTimeMillis();
		for(int a=0;a<list.size();a++) {
			Double scale = NumberFormat.getPercentInstance().parse(list.get(a).getString("scale")).doubleValue();
			for (int b = 0; b < count*scale; b++) {
				Case = new JSONObject(true);
				Case.put("operType", list.get(a).get("operType"));
				Case.put("operSentence", list.get(a).get("operSentence"));
				Cases.add(Case);
			}
		}
		System.out.println(Cases);
		long end=System.currentTimeMillis();
        long time=end-start;
        System.out.println("总计耗时：" + StartClient.formatTime(time));
        
//        List<auditRecordData> auditRecordDataList = new ArrayList<auditRecordData>();
//        for (Entry<String, String> entry : map.entrySet()) {
//        	auditRecordData auditRecordData = new auditRecordData();
//            auditRecordData.setOperType(entry.getKey());
//            auditRecordData.setOperSentence(entry.getValue());
//            auditRecordData.setScale(10);
//            auditRecordDataList.add(auditRecordData);
//        }
//        System.out.println(auditRecordDataList);
        
       
    }
}
